//
//  GKBMainController.m
//  GKBHouse
//
//  Created by  on 12-6-19.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "GKBMainController.h"
//#import "GKBNavigationBar.h"
//#import "LoginController1.h"
//#import "WebServices.h"
//#import "SystemSettting.h"
#import "SettingController.h"

#import "Global1.h"
@interface GKBMainController()


@end

static UIView *_mainView = nil;
GKBMainController *mainCtr = nil;
@implementation GKBMainController
@synthesize equStateTimer;
@synthesize equipments;
@synthesize areaEquipments;
@synthesize roomNames;
@synthesize roomNamess;
@synthesize rooms;
@synthesize roomss;
@synthesize sceneArray;
@synthesize videoArray;
@synthesize updateTarget;
@synthesize updateAction;

+ (UIView *)mainView
{
    return _mainView;
}
+ (void)setMainView:(UIView *)view
{
    _mainView = view;
}
+ (id)mainCtr
{
    return mainCtr;
}
+ (void)setMainCtr:(id)ctr
{
    mainCtr = ctr;
}
+ (void)refreshDevices
{
    GKBMainController *main = [GKBMainController mainCtr];
    if (main) {
        [main refreshDevicesState];
    }
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
- (void)dealloc
{
    [roomView release];
    [networkQueue reset];
    [networkQueue release];
    [_scrollPages release];
    [_houseArray release];
    [_upArrow release];
    [_downArrow release];
    [houseMenuScrollView release];
    
    self.rooms = nil;
    self.sceneArray = nil;
    self.videoArray = nil;
    self.protectArray = nil;
    self.areaEquipments = nil;
    
    self.cameraInfo = nil;
    self.cameraGroup = nil;
    self.cameraInfoArrayDic = nil;
    
    [self removeNotice];
    
    [super dealloc];
}

- (void)releaseTime
{
    if ([self.equStateTimer isValid]) {
        [self.equStateTimer invalidate];
        self.equStateTimer = nil;
    }
}

- (void)dismissView
{
    [self releaseTime];
   
    if ([UIDevice currentDevice].systemVersion.floatValue <= 6.0) {
        [self dismissModalViewControllerAnimated:NO];
        [GKBMainController setMainCtr:nil];
    }
    else
    {
        [self dismissViewControllerAnimated:NO completion:^{
            [GKBMainController setMainCtr:nil];
        }];
    }
    
}
#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [GKBMainController setMainView:self.view];
    // Do any additional setup after loading the view from its nib.
    self.roomNames = [NSMutableArray array];
    self.rooms = [NSMutableDictionary dictionary];
    self.roomNamess = [NSMutableArray array];
    self.roomss = [NSMutableDictionary dictionary];
    self.sceneArray = [NSMutableArray array];
    self.areaEquipments = [NSMutableArray array];
    self.equipments = [NSMutableArray array];
    self.protectArray = [NSMutableArray array];
    
//    [self performSelector:@selector(requestUnread) withObject:nil afterDelay:3];
//    [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(requestUnread) userInfo:nil repeats:YES];
    _houseArray = [[NSMutableArray alloc]init];
//    [self areaEquipmentList];
    [GKBMainController setMainCtr:self];
    
   // [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    
    UIImage *image = [UIImage imageNamed:@"background.png"];
    self.view.layer.contents = (id) image.CGImage;
    [self initTitle];


    [self initRightFrame];
    
    [self addNotice];
    
    
    //加载数据
    if (currentLoginController1.willAutoLogin == NO)
    {
        [self loadList];
    }
    
}



#pragma mark--数据的初始化
- (void)loadList
{
    if ([LoginController1 loginType] == LoginTypeFar) {
//        [self areaEquipmentList];
//        [self equipmentList];
    }
    else
    {
        NSString *saveEqusFile = [AppFile documentsPath:@"euqs.bat"];
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:saveEqusFile];
        [self equipmentListEnd:dic];
    }

}

- (void)startRefreshList
{
    if (self.equipments&&[self.equStateTimer isValid]) {
        [self.equStateTimer invalidate];
        self.equStateTimer = nil;
    }
    NSTimer *timer;
    NSInteger rateTime = 5;//[SystemSettting systemRate];
    timer = [NSTimer scheduledTimerWithTimeInterval:rateTime target:self selector:@selector(equipmentState)userInfo:nil repeats:YES];
    self.equStateTimer = timer;
}

- (void)addNotice
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notice_startRefreshList) name:@"startRefreshList" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notice_stopRefreshList) name:@"stopRefreshList" object:nil];
}

- (void)removeNotice
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"startRefreshList" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"stopRefreshList" object:nil];
}
+ (void)postStartRefresh
{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"startRefreshList" object:nil];
}

+ (void)postStopRefresh
{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"stopRefreshList" object:nil];
}

- (void)notice_startRefreshList
{
    [self releaseTime];
    [self startRefreshList];
}

- (void)notice_stopRefreshList
{
    [self releaseTime];
}

- (void)viewWillAppear:(BOOL)animated
{
    NSLog(@"main view will appear");
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
//    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
//}
#pragma mark - initView
- (void)initTitle
{
    GKBNavigationBar *topBar = [[GKBNavigationBar alloc]init];
    [topBar setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"topBG.png"]]];
    topBar.refreshButton.hidden = YES;
//    topBar.menuButton.hidden = NO;
//    [topBar setTarget:self returnAction:@selector(dismissView) withTitle:NSLocalizedString(@"gkbHome", nil)];
    [self.view addSubview:topBar];
    
    [topBar release];
}
- (void)initUpDownArrow
{
    UIImage *arrowUp = [UIImage imageNamed:@"arrow_up.png"];
    UIImage *arrowDown = [UIImage imageNamed:@"arrow_down.png"];
    
    _upArrow = [[UIImageView alloc]initWithImage:arrowUp];
    [_upArrow setFrame:CGRectMake((kHouseMenuWidth - 26)/2, kMainFrameTop - 10, 26, 10)];
    // _upArrow.center = CGPointMake(kIconWidth/2, 30 + 10);
    [self.view addSubview:_upArrow];
    _upArrow.hidden = YES;
    _downArrow = [[UIImageView alloc]initWithImage:arrowDown];
    [_downArrow setFrame:CGRectMake((kHouseMenuWidth - 26) /2, kMainFrameTop + kMainFrameHeight, 26, 10)];
    //_downArrow.center = CGPointMake(kIconWidth/2, 320-10);
    _downArrow.hidden = YES;
    [self.view addSubview:_downArrow];   
    
    if (houseMenuScrollView.contentSize.height > houseMenuScrollView.frame.size.height) {
        NSLog(@"%f, %f", houseMenuScrollView.contentSize.height, houseMenuScrollView.frame.size.height);
        _downArrow.hidden = NO;
    }
}



#pragma mark--点击左侧菜单显示右边数据
- (void)addHouseMenu:(NSInteger)index title:(NSString *)title image:(NSString *)img selected:(NSString *)selectedImg devices:(NSArray*)array
{
    HouseButton *but = [[HouseButton alloc]init];//[HouseButton buttonWithType:UIButtonTypeRoundedRect];
     CGRect rect = CGRectMake(10, (kHouseMenuHeight)*index, kHouseButtonWidth, kHouseButtonHeight);
    [but setFrame:rect];
    [but setTag:index];
    [but setName:title];
    [but setImgStr:img];  
    [but setSelectedImg:selectedImg];
    //NSArray *deArray = [array copy];
    [but setDevices:array];
    //[deArray release];
    if ([title isEqualToString:@"区域"]) {
        [but.titleLabel setFont:[UIFont boldSystemFontOfSize:22.0]];
    }else{
    [but.titleLabel setFont:[UIFont boldSystemFontOfSize:20.0]];
    }
    [but.titleLabel setAdjustsFontSizeToFitWidth:YES];
    if ([title length]>=3) {
        
        [but.titleLabel setFont:[UIFont boldSystemFontOfSize:15.0]];
        [but.titleLabel setNumberOfLines:2];
    }
    
    [but setTitle:title forState:UIControlStateNormal];
    [but setBackgroundImage:[UIImage imageNamed:img] forState:UIControlStateNormal];
//    [but setBackgroundImage:[UIImage imageNamed:selectedImg] forState:UIControlStateHighlighted];
    [but setState:buttonStateNormal];
    [but addTarget:self action:@selector(houseAction:) forControlEvents:UIControlEventTouchUpInside];
//    [but addTarget:self action:@selector(houseOutsize:) forControlEvents:UIControlEventTouchDragOutside];
    [_houseArray addObject:but];
    [houseMenuScrollView addSubview:but];
    [but release];
}
- (void)initRightFrame
{
    _scrollPages = [[NSMutableArray alloc]init];
    
    devicesScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(kHouseMenuWidth, kMainFrameTop, kDeviceMenuWidth, kMainFrameHeight)];
    [self.view addSubview:devicesScrollView];

    roomView = [[RoomView alloc]init];
    [self.view addSubview:roomView];
    roomView.hidden = YES;
}
- (void)initDevicesTwo
{
    NSInteger pages = [self pageCount];

    [_scrollPages removeAllObjects];
    
    for(UIView *view in devicesScrollView.subviews)
    {
        [view removeFromSuperview];
    }
    
    
    CGFloat contentHeight = houseMenuScrollView.contentSize.height;
    NSInteger startX = 15;
    NSInteger rowMax = kDeviceMenuWidth/kViewWidth;//每页横排可容纳个数
    
    for (int page = 0; page<pages; page++) {
        UIScrollView *pageView = [[UIScrollView alloc]initWithFrame:CGRectMake(page * kDeviceMenuWidth, 0, kDeviceMenuWidth, kMainFrameHeight)];
        for (int room = 0; room <[_houseArray count]; room++) {// room 是y轴
            HouseButton *house = [_houseArray objectAtIndex:room];
            NSInteger count = [house.devices count];
            int deveceIndex = page*rowMax;//当前页起始电器
            int capacityMax = deveceIndex+rowMax;//当前面可放置的最后一个电器
            int maxDevces = capacityMax<count?(capacityMax):count;//当前页可容纳电器总数VS当电器总数
            
            if (deveceIndex>0 && deveceIndex < count) {//当大于一页，有向左的箭头
                UIImageView *toLeft = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"toLeft.png"]];
                [toLeft setFrame:CGRectMake(0, 0, 8, 16)];
                [toLeft setCenter:CGPointMake(startX/2, room*kViewHeight + kIconHeight/2)];
                [pageView addSubview:toLeft];
                [toLeft release];
            }
            //还有多余电器，提示向右箭头
            if (capacityMax < count) {//还有多余电器，放在下一页
                UIImageView *toRight = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"toRight.png"]];
                [toRight setFrame:CGRectMake(0, 0, 8, 16)];
                [toRight setCenter:CGPointMake(kDeviceMenuWidth - 15, room*kViewHeight + kIconHeight/2)];
                [pageView addSubview:toRight];
                [toRight release];
            }
            
            for (; deveceIndex<maxDevces; deveceIndex++) {//device是x轴
               // NSArray *array = house.devices;
                
               // NSLog(@"%d, %@", count, array);
                if (deveceIndex<[house.devices count]) {
                    CGRect rect = CGRectMake(startX + (deveceIndex%rowMax)*kViewWidth, room*kViewHeight, kViewWidth, kViewHeight);
                    NewEquipment *equipment = [house.devices objectAtIndex:deveceIndex];
                    DeviceView *deviceView = [[DeviceView alloc]initWithFrame:rect withEqu:equipment];
                    BOOL open = NO;
                    if ([equipment.state isEqualToString:@"1"]) {
                        open = YES;
                    }
                    if ([equipment.state isEqualToString:@"2"]) {
                        open = NO;
                    }
                    [deviceView setDeviceOn:open];
                    [pageView addSubview:deviceView];
                    [deviceView release];
                }
                
            }
            
        }
        [pageView setContentSize:CGSizeMake(kDeviceMenuWidth, contentHeight)];
        pageView.delegate = self;
        [_scrollPages addObject:pageView];
        [devicesScrollView addSubview:pageView];
        [pageView release];
    }
    
    [devicesScrollView setContentSize:CGSizeMake(kDeviceMenuWidth*pages, kMainFrameHeight)];

    for (UIScrollView *page in _scrollPages) {
        page.contentOffset = CGPointMake(page.contentOffset.x, houseMenuScrollView.contentOffset.y);
    }

    devicesScrollView.pagingEnabled = YES;
    devicesScrollView.showsHorizontalScrollIndicator = NO;
    devicesScrollView.showsVerticalScrollIndicator = NO;
    devicesScrollView.delegate = self;
    devicesScrollView.directionalLockEnabled= YES;
    
}
- (void)initDevices
{
    _pageViews = [[NSMutableArray alloc]init];
    
    devicesScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(kHouseMenuWidth, 30, kDeviceMenuWidth, 290)];
 //   [devicesScrollView setContentSize:CGSizeMake(70, 390)];
//    CGRect rect = CGRectMake(0, 0, 400, 290);
    NSInteger width = 0;
    UIView *view = [[UIView alloc]init];
    for (int i = 0; i<[_houseArray count]; i++) {// i 是y轴
        HouseButton *house = [_houseArray objectAtIndex:i];
        for (int j = 0; j<[house.devices count]; j++) {//j是x轴
          //  NSString *title = [NSString stringWithFormat:@"%d:%d",i,j];
            CGRect rect = CGRectMake(2 + j*kViewWidth, 10 + i*kViewHeight, kViewWidth, kViewHeight);
           // NSString *type = [house.devices objectAtIndex:j];
            
            DeviceView *device = [[DeviceView alloc]initWithFrame:rect withEqu:nil];

            if (width < 2 + (1 + j)*kViewWidth) {
                width = 2 + (1 + j)*kViewWidth;
            }
            [view addSubview:device];
        
        }      
    }
    [view setFrame:CGRectMake(0, 0, width, houseMenuScrollView.contentSize.height)];
    [devicesScrollView addSubview:view];
//    for (int i= 0; i<4; i++) {
//        rect = CGRectMake(i*410 + 5, 0, 400, 290);
//        UIView *view = [[UIView alloc]initWithFrame:rect];
//        [view setBackgroundColor:[UIColor blueColor]];
//        [_pageViews addObject:view];
//        [devicesScrollView addSubview:view];
//    }
    [devicesScrollView setContentSize:CGSizeMake(width, houseMenuScrollView.contentSize.height)];
    devicesScrollView.pagingEnabled = YES;
  //  devicesScrollView.showsHorizontalScrollIndicator = NO;
  //  devicesScrollView.showsVerticalScrollIndicator = NO;
    devicesScrollView.delegate = self;
    devicesScrollView.directionalLockEnabled= YES;
    [self.view addSubview:devicesScrollView];
}
- (NSInteger)pageCount
{
    NSInteger maxCount = 0;
    for (HouseButton *house in _houseArray) {
        NSInteger count = [house.devices count];
        if (maxCount < count) {
            maxCount = count;
        }
    }
    NSInteger page = (maxCount - 1)/5 + 1;
    return page;
}
- (void)houseAction:(HouseButton *)but
{
    NSLog(@"in:%d", but.tag);
    NSInteger current = but.tag;
   
    if (but.state == buttonStateNormal || but.state == buttonStateFalse) {
        but.state = buttonStateSelect;
        //[but setBackgroundColor:[UIColor redColor]];
        
        for (HouseButton *button in _houseArray) {
            if (button.tag == current) {
                [button setState:buttonStateSelect];
                // [button setBackgroundColor:[UIColor grayColor]];
                UIImage *selected = nil;//[UIImage imageNamed:@"gray.png"];
                selected = [UIImage imageNamed:button.selectedImg];
                
                [button setBackgroundImage:selected forState:UIControlStateNormal];
               // [button setEnabled:YES];
            }
            else
            {
                [button setState:buttonStateFalse];
                UIImage *gray = [UIImage imageNamed:@"gray.png"];
//                gray = [UIImage imageNamed:button.selectedImg];
                [button setBackgroundImage:gray forState:UIControlStateNormal];
                [button setEnabled:NO];
                [button setEnabled:YES];
//                [button setImage:gray forState:UIControlStateNormal];
                
            }
        }
        
        [self openRoom:but];
            
    }
    else
    {
        //[self closeRoom];
    }
    
    
}
- (void)houseOutsize:(HouseButton *)sender
{
    NSLog(@"out");
}

- (void)openRoom:(HouseButton*)house
{   
   // houseMenuScrollView.scrollEnabled = NO;
    devicesScrollView.hidden = YES;
    roomView.hidden = NO;
    [roomView roomView:house];   
    [roomView setTarget:self action:@selector(closeRoom)];   
     
}
- (void)refreshRoomView
{
    //房间电器状态更新，包括场情
    if (roomView.room && roomView.hidden == NO) {
        NSString *key = roomView.room.name;
        HouseButton *room = roomView.room;
        //更新情景
        if ([key isEqualToString:NSLocalizedString(@"scene", nil)]) {
            room.devices = self.sceneArray;
        }
        else if([key isEqualToString:NSLocalizedString(@"func", nil)])
        {
            room.devices = self.videoArray;
        }
        else if([key isEqualToString:NSLocalizedString(@"area", nil)])
        {
            room.devices = self.areaEquipments;
        }
        else
        {
            room.devices = [self.rooms objectForKey:key];
        }
        
        
        [roomView roomView:room];
    }
}
- (void)closeRoom
{
    roomView.hidden = YES;

    NSLog(@"close");
    for (HouseButton *button in _houseArray) {
        [button setState:buttonStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:button.imgStr] forState:UIControlStateNormal];
        // [button setBackgroundColor:[UIColor whiteColor]];
        [button setEnabled:YES];
    }
    devicesScrollView.hidden = NO;
    houseMenuScrollView.scrollEnabled = YES;
    //[self initDevicesTwo];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"%f,%f", scrollView.contentOffset.x, scrollView.contentOffset.y);
    if (scrollView == houseMenuScrollView) {
        for (UIScrollView *page in _scrollPages) {
            page.contentOffset = CGPointMake(page.contentOffset.x, scrollView.contentOffset.y);
        }
       // devicesScrollView.contentOffset = CGPointMake(devicesScrollView.contentOffset.x, scrollView.contentOffset.y);//scrollView.contentOffset;
    }
    else if(scrollView != devicesScrollView)
    {
        houseMenuScrollView.contentOffset = CGPointMake(0, scrollView.contentOffset.y);
        for (UIScrollView *page in _scrollPages) {
            page.contentOffset = CGPointMake(page.contentOffset.x, scrollView.contentOffset.y);
        }
//        if(devicesScrollView.decelerating && bPageRefreshed == NO)
//        {
//            CGFloat pageWidth = devicesScrollView.frame.size.width;
//            NSInteger page = floor((devicesScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
//            if (_pageControl.numberOfPages >= page) {
//           //     [self scrollToPage:page animated:YES];
//            }
//            
//            if (_pageControl.currentPage != page) {
//                bPageRefreshed = YES;
//                _pageControl.currentPage = page;
//                
                // load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
       //         [self performSelectorOnMainThread:@selector(loadAdjacencyPages:) 
      //                                 withObject:[NSNumber numberWithInteger:page] 
      //                              waitUntilDone:NO];
 //           }
           
  //      }
        
    }
    
    if (houseMenuScrollView.contentSize.height > houseMenuScrollView.frame.size.height) {
        _upArrow.hidden = YES;
        _downArrow.hidden = YES;
        if (houseMenuScrollView.contentOffset.y > 0) {
            _upArrow.hidden = NO;
        }
        CGFloat offsetHeight = houseMenuScrollView.contentSize.height - houseMenuScrollView.frame.size.height;
        if (houseMenuScrollView.contentOffset.y < offsetHeight) {
            NSLog(@"%f, %f", houseMenuScrollView.contentOffset.y, offsetHeight);
            _downArrow.hidden = NO;
        }
        
    }
    
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    _upArrow.hidden = YES;
    _downArrow.hidden = YES;
}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
	bPageRefreshed = NO;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{	
	bPageRefreshed = YES;
}
- (void)scrollToPage:(NSInteger)page animated:(BOOL)animated
{
    id pageObj = [_pageViews objectAtIndex:page];
    UIView * pageView = [pageObj isKindOfClass:[UIView class]] ? pageObj : nil;
    [devicesScrollView scrollRectToVisible:pageView.frame animated:YES];
}

- (void)willRemoveSubview:(UIView *)subview
{
    NSLog(@"remove");
}


- (void)initScene
{
//    self.sceneArray = [NSMutableArray array];
    [self.sceneArray removeAllObjects];
    NewEquipment *equipment = [[NewEquipment alloc]init];
    [equipment setName:NSLocalizedString(@"allOff", nil)];
    
    NSString *type = [NSString stringWithFormat:@"%d", DeviceTypeAll];    
    [equipment setType:type];
    [equipment setSwitchId:@"0"];
    [equipment setTagName:NSLocalizedString(@"scene", nil)];
    [equipment setRegulate:@"1"];
    [equipment setState:kStateOFF];
    [self.sceneArray addObject:equipment];
    [equipment release];

    NSString *sceneFile = [AppFile sceneFile];
    NSMutableDictionary *allScene = [NSMutableDictionary dictionaryWithContentsOfFile:sceneFile];
  
    NSString *scene = NSLocalizedString(@"scene", nil);
    for (int i=1; i<7; i++) {
        NSString *scenId = [NSString stringWithFormat:@"%d", i];
        NSString *name = [scene stringByAppendingFormat:@"%d",i];
        NSMutableArray *openEqus = [NSMutableArray array];
        NSString *key = [NSString stringWithFormat:@"%d",i];
        NewEquipment *equipment = [[NewEquipment alloc]init];
        
        [equipment setName:name];
        NSString *type = [NSString stringWithFormat:@"%d", DeviceTypeScene];
        [equipment setType:type];
        [equipment setSwitchId:scenId];
        [equipment setRegulate:@"3"];
        [equipment setState:kStateOFF];
        [equipment setOpenEques:openEqus];
        NSLog(@"____scene____");
        if (allScene) {
            NSMutableDictionary *scene = [allScene objectForKey:key];
            if (scene) {
                name = [scene objectForKey:@"name"];
                openEqus = [scene objectForKey:@"OpenEqus"];
                [equipment setName:name];
                [equipment setOpenEques:openEqus];
                if ([openEqus count]>0) {
                    [self.sceneArray addObject:equipment];
                }
                
            }
            
        }
        
        [equipment release];
        
    }
//    for (int i = 0; i<9; i++) {
//        Equipment *equipment = [[Equipment alloc]init];
//        NSString *sid = [NSString stringWithFormat:@"%d", i+1];
//        NSString *fomat = @"情景%d";
//        NSString *name = [NSString stringWithFormat:fomat, i+1];
//        [equipment setName:name];
//        NSString *type = [NSString stringWithFormat:@"%d", DeviceTypeScene];
//        [equipment setType:type];
//        [equipment setSwitchId:sid];
//        [equipment setTagName:NSLocalizedString(@"scene", nil)];
//        [equipment setRegulate:@"3"];
//        [equipment setState:kStateOFF];
//        [self.sceneArray addObject:equipment];
//        [equipment release];
//    }
}

- (void)initVideo//跳转去视频
{
    self.videoArray = [NSMutableArray array];
    [self.videoArray removeAllObjects];
//    [self.videoArray removeAllObjects];
//    Equipment *equipment = [[Equipment alloc]init];
//    [equipment setName:NSLocalizedString(@"video", nil)];
//    
//    NSString *type = [NSString stringWithFormat:@"%d", DeviceTypeVideo];
//    [equipment setType:type];
//    [equipment setSwitchId:@"0"];
//    [equipment setTagName:NSLocalizedString(@"video", nil)];
//    [equipment setRegulate:@"1"];
//    [equipment setState:kStateOFF];
//    equipment.target = self;
//    equipment.selector = @selector(openCameraInfo:);
//    [self.videoArray addObject:equipment];
//    [equipment release];
    
    NSSortDescriptor *_sorter  = [[NSSortDescriptor alloc] initWithKey:@"ucOrderId"
                                                             ascending:YES];
    self.cameraGroup = [self.cameraGroup sortedArrayUsingDescriptors:[NSArray arrayWithObjects:_sorter, nil]];
    
    
    for (NSDictionary *dic in self.cameraGroup) {
        
        NSString *name = [dic objectForKey:@"ucName"];
        NSString *ucId = [dic objectForKey:@"ucId"];
        
        NewEquipment *equipment = [[NewEquipment alloc]init];
        NSLog(@"equipment==%@",equipment);
        NSString *type = [NSString stringWithFormat:@"%d", DeviceTypeVideo];
        [equipment setType:type];
        [equipment setSwitchId:ucId];
        [equipment setTagName:NSLocalizedString(@"video", nil)];
        [equipment setName:name];
        [equipment setRegulate:@"1"];
        [equipment setState:kStateOFF];
        equipment.target = self;
        equipment.selector = @selector(openCameraInfo:);
        [self.videoArray addObject:equipment];
        [equipment release];
    }
    [_sorter release];
}

- (void)initProtect//安防
{
//    Equipment *equipment = [[Equipment alloc]init];
//    [equipment setName:@"安防"];
//    
//    NSString *type = [NSString stringWithFormat:@"%d", DeviceTypeProtect];
//    [equipment setType:type];
//    [equipment setSwitchId:@"0"];
//    [equipment setTagName:NSLocalizedString(@"scene", nil)];
//    [equipment setRegulate:@"0"];
//    [equipment setState:kStateOFF];
//    
//    [self.protectArray addObject:equipment];
//    [equipment release];
    
    NSMutableArray *array = self.equipments;
    
    
    NSInteger count = [self.protectArray count];
    if (count == 1) {
        NewEquipment *equ = [self.protectArray objectAtIndex:0];
        equ.protectId = 0;
        equ.name = @"布防";
        
        
        
    }
    else if(count >1)
    {
        NSInteger index = 1;
        
        for (NewEquipment *equ in self.protectArray) {
            equ.protectId = index;
            
            NSString *bufang = [@"布防" stringByAppendingFormat:@"%d", equ.protectId];
            equ.name = bufang;
            
            index++;
        }
    }
    
    
    for (NewEquipment *equ in self.protectArray) {
        
        for (NSMutableDictionary *equDic in array) {//重设置安防名称和修改安防的所属房间
            NSString *switchId = [equDic objectForKey:@"switchId"];
            
            if ([switchId isEqualToString:equ.switchId]) {
                [equDic setObject:equ.name forKey:@"name"];
//                [equDic setObject:NSLocalizedString(@"func", nil) forKey:@"tagName"];
                [equDic setObject:@"" forKey:@"tagName"];
            }
            
        }
        
        [self.videoArray addObject:equ];
    }
    
}


#pragma mark-左边菜单数据
- (void)initRoomsMenu
{
    [houseMenuScrollView removeFromSuperview];
    houseMenuScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, kMainFrameTop, kHouseMenuWidth, kMainFrameHeight)];
    
    CGRect rect = CGRectMake(2, 10, 56, 56);
    int i = 0;
//    [self addHouseMenu:i++ title:@"情景" image:@"brown.png"selected:@"brownSelected.png" devices:self.sceneArray];
//    [self addHouseMenu:i++ title:@"情景" image:@"brown.png"selected:@"brownSelected.png" devices:self.sceneArray];
//    [self addHouseMenu:i++ title:@"情景" image:@"brown.png"selected:@"brownSelected.png" devices:self.sceneArray];
//    [self addHouseMenu:i++ title:@"情景" image:@"brown.png"selected:@"brownSelected.png" devices:self.sceneArray];
    for (NSString *key in self.roomNames) {
      //  NSLog(@"%@", key);
        NSArray *array = [self.rooms objectForKey:key];
       // NSLog(@"%@", array);
        [self addHouseMenu:i++ title:key image:@"blue.png" selected:@"blueSelected.png" devices:array];
    }
    //[self initScene];
    [self addHouseMenu:i++ title:NSLocalizedString(@"scene", nil) image:@"brown.png"selected:@"brownSelected.png" devices:self.sceneArray];
    //[self initVideo];
   // [self initProtect];
    [self addHouseMenu:i++ title:NSLocalizedString(@"func", nil) image:@"purple.png"selected:@"purpleSelected.png" devices:self.videoArray];
    
    
    if (areaEquipments.count > 0)
    
    {
        [self addHouseMenu:i++ title:NSLocalizedString(@"area", nil) image:@"huangss@3x.png"selected:@"black" devices:areaEquipments];
    }
    
    rect = CGRectMake(10, (kViewHeight)*i, kIconWidth, kIconHeight);
    [houseMenuScrollView setContentSize:CGSizeMake(kHouseMenuWidth, (kViewHeight)*i)];
    houseMenuScrollView.delegate = self;
    [self.view addSubview:houseMenuScrollView];    
    [self initUpDownArrow];
}
#pragma mark - 电器设备数据
- (void)equipmentList
{
    [self releaseTime];
    NSInteger sortType = [SystemSettting sortType];
    NSString *sessionId = [LoginController1 sessionID];
    
    NSString *fomat = @"[{\"sessionId\":\"%@\", \"obway\":\"%d\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId, sortType];
    NSString *errorType = [OperationTip errorType:ErrorTypeNetworkFail];
    
    [WebServices requestStartOrder:@"getEquipmentList" body:body target:self action:@selector(equipmentListEnd:) errorTip:errorType];
}
- (void)equipmentListEnd:(NSDictionary *)dic
{
    NSLog(@"equipmentListEnd：%@", dic);
   // NSString *result = [dic objectForKey:@"result"];
    NSNumber *result = [dic objectForKey:@"result"];
    NSArray *data = [dic objectForKey:@"data"];
//    self.equipments = data;
    if (self.equipments) {
        [self.equipments removeAllObjects];
    }
    else
    {
        self.equipments = [[NSMutableArray alloc] init];
        
    }
    self.equipments = data;
    if ([data count]>0) {
        NSMutableArray *array = [NSMutableArray array];
        for (NSDictionary *dic in data) {
            NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithDictionary:dic];
            [array addObject:mutDic];
        }
        self.equipments = array;
    }
//    NSLog(@"%@,%@", result, sessionId);
    [self.roomNames removeAllObjects];
    [self.rooms removeAllObjects];
    [self.protectArray removeAllObjects];
    if (result.integerValue == 0) {
        NSString *version = [dic objectForKey:@"version"];
        if (version && [version isEqualToString:@"ds"]) {
            //ds:  此主机有定时功能 de:  此主机为默认旧主机，没有定时功能
            [SettingController setHaveTimeSetting:YES];
        }
        else{
            [SettingController setHaveTimeSetting:NO];
        }
        NSString *saveEqusFile = [AppFile documentsPath:@"euqs.bat"];
        [dic writeToFile:saveEqusFile atomically:YES];
        for (NSDictionary *equ in data) {
            NSString *name = [equ objectForKey:@"name"];
            NSString *type = [equ objectForKey:@"type"];
            NSString *switchId = [equ objectForKey:@"switchId"];
            NSString *tagName = [equ objectForKey:@"tagName"];
    
//            NSString *sting = [NSString stringWithCString:tagName.UTF8String encoding:NSUTF8StringEncoding];
//            NSLog(@"r:%@",sting);
            
            NSString *regulate = [equ objectForKey:@"regulate"];
            NewEquipment *equipment = [[NewEquipment alloc]init];
            [equipment setName:name];
            [equipment setType:type];
            [equipment setSwitchId:switchId];
            [equipment setTagName:tagName];
            [equipment setRegulate:regulate];
            [equipment setState:kStateOFF];
            
            if ([type isEqualToString:@"9"]) {//安防
                [self.protectArray addObject:equipment];
            }
            else
            {
                NSMutableArray *room = [self.rooms objectForKey:tagName];
                if (room) {
                    [room addObject:equipment];
                }
                else
                {
                    [self.roomNames addObject:tagName];
                    NSMutableArray *room = [[NSMutableArray alloc]init];
                    [room addObject:equipment];
                    [self.rooms setObject:room forKey:tagName];
                    [room release];
                }
            }
            
            [equipment release];
        } 
        
        
        [self getUserCameraList:^{
            [_houseArray removeAllObjects];
            
            
            //左边数据
            [self initRoomsMenu];

            
        
            [self initDevicesTwo];
            
            //[self equipmentState];//取得设备状态
            //[self startRefreshList];//启动定时刷新设备状态
            
            //[self getCameraInfoArray];
        }];
        
        [self getCameraInfo];//视频客户端匹配信息
    }
    else
    {
        NSString *errorType = [OperationTip errorType:ErrorTypeServerReturnFail];
        [iToast showTip:errorType gravity:iToastGravityBottom];
    }
    
}

#pragma mark - 区域数据
- (void)areaEquipmentList
{

    NSString *sessionId = [LoginController1 sessionID];
    
    NSString *fomat = @"[{\"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId];
    NSString *errorType = [OperationTip errorType:ErrorTypeNetworkFail];
    
    [WebServices requestStartOrder:@"getRelevanceHosts" body:body target:self action:@selector(areaEquipmentListEnd:) errorTip:errorType];
}

- (void)areaEquipmentListEnd:(NSDictionary *)dic
{
    
    NSLog(@"equipmentListEnd：%@", dic);
//     NSString *result = [dic objectForKey:@"result"];
//    NSNumber *result = [dic objectForKey:@"result"];
    NSArray *data = [dic objectForKey:@"relevanceHosts"];
//    NSLog(@"data主机名称＝＝＝＝%@",data);
    if (self.areaEquipments) {
        [self.areaEquipments removeAllObjects];
    }
    else
    {
        self.areaEquipments = [[NSMutableArray alloc] init];
    }
//    int i = 0;
//     Equipment *equipment = [[Equipment alloc]init];
//    NSString *displayName = [[NSUserDefaults standardUserDefaults] objectForKey:@"displayName"];
//    if (displayName.length > 0) {
//        [equipment setName:displayName];
//    }else{
//        [equipment setName:@"主机"];
//    }
//    
//    [equipment setType:@"13"];
//    //        [equipment setRegulate:regulate];
//    [equipment setState:kStateOFF];
//    [equipment setSwitchId:[NSString stringWithFormat:@"100"]];
//    [self.areaEquipments addObject:equipment];
    for (NSDictionary *equ in data) {
        NSString *displayName = [equ objectForKey:@"displayName"];
        NSString *orderId = [equ objectForKey:@"orderId"];
        NSString *relevanceUserName = [equ objectForKey:@"relevanceUserName"];
        NSString *relevanceUserPass = [equ objectForKey:@"relevanceUserPass"];
        NSString *hostnum = [equ objectForKey:@"relevanceHostnum"];
//        NSLog(@"主机名称＝＝＝＝%@",relevanceUserName);
//        NSString *regulate = [equ objectForKey:@"regulate"];
        NewEquipment *equipment = [[NewEquipment alloc]init];
        [equipment setName:displayName];
        [equipment setOrderId:orderId];
        [equipment setRelevanceUserName:relevanceUserName];
        [equipment setRelevanceUserPass:relevanceUserPass];
        [equipment setType:@"14"];
//        [equipment setRegulate:regulate];
        [equipment setState:kStateOFF];
        [equipment setSwitchId:hostnum];
        equipment.target = self;
//        equipment.selector = @selector(openAreaInfo:);
        if ([hostnum isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"hostnum"]]) {
            [self.areaEquipments insertObject:equipment atIndex:0];
        }else{
        [self.areaEquipments addObject:equipment];
        }
        [equipment release];
    }
//    [self refreshDevicesState];
    
//    [self.areaEquipments release];
}

//- (void)openAreaInfo:(Equipment *)equ
//{
//    
//}
#pragma mark - 电器设备开关状态
- (void)equipmentStateWidthTip
{
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId];
    
    NSString *tip = NSLocalizedString(@"refreshing", nil);
    [iToast showTip:tip gravity:iToastGravityBottom];
    
    NSString *errorTip = NSLocalizedString(@"refresh error", nil);
    [WebServices requestStartOrder:@"getEquipmentState" body:body target:self action:@selector(equipmentStateWidthTipEnd:) errorTip:errorTip];
}
- (void)equipmentStateWidthTipEnd:(NSDictionary *)dic
{
    [WebServices setShowConnectting:NO];//关闭提示
    NSLog(@"equipmentStateEnd");
    // NSString *result = [dic objectForKey:@"result"];
    NSNumber *result = [dic objectForKey:@"result"];
    NSArray *states = [dic objectForKey:@"states"];
    if (result.integerValue == 0) {
        [self setRoomsState:states];
        NSString *tip = NSLocalizedString(@"refresh success", nil);
        [iToast showTip:tip gravity:iToastGravityBottom];
    }
    else
    {
        NSString *tip = NSLocalizedString(@"refresh error", nil);
        [iToast showTip:tip gravity:iToastGravityBottom];

    }
    
}
- (void)equipmentState
{
    
    if(self.state == RefreshStateLoading)
        return;
    self.state = RefreshStateLoading;
    
    NSString *refresh = @"1";
    if (self.refreshTime == 12) {
        refresh = @"2";
    }

//    NSLog(@"____equipmentState:%d:%@", self.refreshTime, refresh);
    
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sessionId\":\"%@\",\"refresh\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId, refresh];
    [WebServices requestStartOrder:@"getEquipmentState" body:body target:self action:@selector(equipmentStateEnd:) errorTip:@"No Prompt"];
    
}
- (void)equipmentStateEnd:(NSDictionary *)dic
{
    self.state = RefreshStateEnd;
    
    [WebServices setShowConnectting:NO];//关闭提示
  
    // NSString *result = [dic objectForKey:@"result"];
    NSNumber *result = [dic objectForKey:@"result"];
    NSArray *states = [dic objectForKey:@"states"];
    if (result.integerValue == 0) {
        [self setRoomsState:states];
    }
//    for (NSDictionary *stateDic in states) {
//        NSString *switchId = [stateDic objectForKey:@"switchId"];
//        NSString *state = [stateDic objectForKey:@"state"];
//    }
    //    NSLog(@"%@,%@", result, sessionId);
    
    self.refreshTime++;
    if (self.refreshTime > 12) {
        self.refreshTime = 0;
    }
    
}
- (void)setRoomsState:(NSArray *)states
{
    if (self.updateTarget&&self.updateAction) {
        [self.updateTarget performSelector:self.updateAction withObject:states];
    }
    for (NSDictionary *stateDic in states) {
        NSString *switchId = [stateDic objectForKey:@"switchId"];
        NSString *state = [stateDic objectForKey:@"state"];
        for (id key in self.rooms) {
            NSArray *equs = [self.rooms objectForKey:key];
            BOOL find = NO;
            for (NewEquipment *equ in equs) {
                if ([equ.switchId isEqualToString:switchId]) {
                    equ.state = state;
                    find = YES;
                    break;//找到退出电器组循环
                }
            }
            if (find) {
                break;//找到退出房间循环
            }
        }
        
        for (NewEquipment *equ in self.protectArray) {
            if ([equ.switchId isEqualToString:switchId]) {
                equ.state = state;
                break;//找到退出电器组循环
            }
        }
    }
    
    [self refreshDevicesState];
}
- (void)refreshDevicesState
{
    //更新主界面电器状态
    //[self initDevicesTwo];
    //更新房间内的电器状态
    [self refreshRoomView];
    
    
}
- (void)updateStateByNet
{
    [self equipmentState];
}
- (void)updateStateByNetTarget:(id)target action:(SEL)action
{
    self.updateTarget = target;
    self.updateAction = action;
    [self equipmentState];
}

+ (void)updateEqu:(NewEquipment *)euq button:(UIButton *)but states:(NSArray*)states
{
    for (NSDictionary *stateDic in states) {
        NSString *switchId = [stateDic objectForKey:@"switchId"];
        NSString *state = [stateDic objectForKey:@"state"];
        if ([switchId isEqualToString:euq.switchId]) {
            euq.state = state;
            if ([euq.state isEqualToString:@"1"]) {
                [DeviceView setDeivceOnOff:euq button:but State:YES];
            }
            else
            {
                [DeviceView setDeivceOnOff:euq button:but State:NO];
            }
            break;
        }
    }
}

#pragma mark - 摄像头数据

- (void)getUserCameraList:(void(^)(void))endresult
{
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId];
    // [WebServices setShowConnectting:NO];//关闭提示
    
    [WebServices requestSynStartOrder:@"getUserCameraList" body:body result:^(NSDictionary *dic) {
        [WebServices setShowConnectting:NO];
        NSNumber *result = [dic objectForKey:@"result"];
        if (result.integerValue == 0) {
            NSArray *data = [dic objectForKey:@"cameraGroup"];
            if (data) {
                self.cameraGroup = [NSMutableArray arrayWithArray:data];
            }
        }
        if (endresult) {
            endresult();
        }
    }];
}

- (void)getUserCameraListEnd:(NSDictionary *)dic
{
    [WebServices setShowConnectting:NO];//关闭提示
    // NSString *result = [dic objectForKey:@"result"];
    
}

- (void)getCameraInfoArray
{
    self.cameraInfoArrayDic = [NSMutableDictionary dictionary];
    for (NSDictionary *dic in self.cameraGroup) {
        NSString *ucid = [dic objectForKey:@"ucId"];
        if (ucid == nil) {
            continue;
        }
        NSString *ucidStr = [NSString stringWithFormat:@"%@", ucid];
        NSString *sessionId = [LoginController1 sessionID];
        NSString *fomat = @"[{\"sessionId\":\"%@\", \"ucId\":\"%@\", \"osFlag\":\"ios\"}]";
        NSString *body = [NSString stringWithFormat:fomat, sessionId, ucid];
        
        [WebServices requestSynStartOrder:@"getCameraInfo" body:body result:^(NSDictionary *dic) {
            NSNumber *result = [dic objectForKey:@"result"];
            if (result.integerValue == 0) {
                NSArray *data = [dic objectForKey:@"cameraInfo"];
                if ([data count]>0) {
                    NSDictionary *cameraInfo = [data objectAtIndex:0];
                    self.cameraInfo = cameraInfo;
                    if (cameraInfo) {
                        [self.cameraInfoArrayDic setObject:cameraInfo forKey:ucidStr];
                    }
                }
            }
        }];
    }
    
    
}

- (void)getCameraInfo
{
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sessionId\":\"%@\", \"osFlag\":\"ios\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId];
     [WebServices setShowConnectting:YES];//关闭提示
    [WebServices requestStartOrder:@"getCameraInfo" body:body target:self action:@selector(getCameraInfoEnd:) errorTip:@"No Prompt"];
    
}
- (void)getCameraInfoEnd:(NSDictionary *)dic
{
    [WebServices setShowConnectting:YES];//关闭提示
    // NSString *result = [dic objectForKey:@"result"];

    NSNumber *result = [dic objectForKey:@"result"];
    if (result.integerValue == 0) {
        NSArray *data = [dic objectForKey:@"cameraInfo"];
        if ([data count]>0) {
            NSLog(@"cameraInfo===%@",data);
            NSDictionary *cameraInfo = [data objectAtIndex:0];
            self.cameraInfo = cameraInfo;
        }
    }
    
}

- (void)openCameraInfo:(NewEquipment *)equ
{
    NSString *ucId = [NSString stringWithFormat:@"%@", equ.switchId];
    NSDictionary *dic = [self.cameraInfoArrayDic objectForKey:ucId];
    
    if (dic) {
        NSString *urlScheme = [dic objectForKey:@"iosURLScheme"];
        NSLog(@"urlScheme===%@",urlScheme);
        //下载界面
        NSString *downloadString = [dic objectForKey:@"iosAppstoreURL"];
        
        if ([urlScheme isEqualToString:@"default"] || [downloadString isEqualToString:@"default"]) {
            [iToast showTip:@"用户没安装摄像头" gravity:iToastGravityCenter];
            return;
        }
        NSURL *url = [NSURL URLWithString:urlScheme];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
        else
        {
            url = [NSURL URLWithString:downloadString];
            [[UIApplication sharedApplication] openURL:url];
        }
    }
    
}

@end
